import { observable, action } from "mobx";
import * as Apis from "../../apis/docLibraryApi";
import { ListViewPage } from "weaver-mobile-page";

class DocLibraryStore {

  @observable drawerOpen = false;
  @observable selected = ""; //选中的tab
  @observable selectedItem = [];
  @observable list = new ListViewPage.Store({ route: '/docLabrary' });
  @observable tabs = [];
  @observable number = 0;//展示的tab页
  @observable loading = false;

  //tab下拉的按钮点击事件
  @action.bound
  showDrawer() {
    this.drawerOpen = true;
  }

  @action
  setState = (params = {}) => {
    Object.keys(params).forEach(key => {
      this[key] = params[key];
    });
  }

  //打开tab的所有展示数据
  @action.bound
  onOpenChange() {
    this.drawerOpen = false;
    const params = {
      odocType: this.selectedItem.join(",")
    }
    this.getList(params);
  }

  //抽屉组件的选中item
  @action.bound
  itemSelected(e) {
    e.preventDefault();
    e.stopPropagation();
    const id = e.currentTarget.getAttribute("data-id");
    this.selectedItem = []
    this.selectedItem.push(id);
    this.tabs.map((item, index) => {
      if (item.id == id) {
        this.number = index;
      }
    })
    this.onOpenChange();
  }

  //获取数据表格
  @action.bound
  getList(datas = {}, isAnvanced = false) {
    this.loading = true;
    const params = {
      ...datas,
    }
    Apis.getList(params).then(data => {
      if (data.sessionkey) {
        if (isAnvanced) {
          this.number = 0;
          this.selectedItem = [];
        }
        this.list.getData({ dataKey: data.sessionkey }, () => {
          this.loading = false;
        }, true);
      }
    })
  }

  //获取tabs
  @action.bound
  getTabs() {
    Apis.getTabs().then(data => {
      if (data.countByOdocType) {
        data.countByOdocType.dataList.unshift({ count: 0, id: "more", odoctype: "more", showname: "全部" })
        this.tabs = this.changeTabs(data.countByOdocType.dataList, data.totalCount);
      }
    })
  }

  //获取重公文中心进来时的页面
  @action.bound
  getTabKey(key) {
    this.selected = key;
    this.tabs.map((item, index) => {
      if (item.id == key) {
        this.number = index;
      }
    })
  }

  @action.bound
  tabClick(tab) {
    this.selected = tab.id;
    let params = {}
    if (tab.id != "more") {
      params = { odocType: tab.id };
    } else {
      params = { odocType: "" };
    }
    this.getList(params);
    this.changeTabs(this.tabs)
  }

  //数据格式不匹配 为了符合组件转换数据格式
  @action.bound
  changeTabs(tabs) {
    tabs.map((item, index) => {
      item.title = item.showname;
      if (item.id === this.selected) {
        this.number = index;
      }
    })
    return tabs;
  }

  @action.bound
  initData() {
    this.number = 0;
    this.selectedItem = [];
  }

}

export default DocLibraryStore;
